package com.taptech.doufu.ui.view;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.taptech.doufu.util.FetchResourceUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.SinaWeiboActivity;
import com.taptech.doufu.ui.adapter.TTShareAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.Constant.WXData;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.QQService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import com.douhuayuedu.douhua.wxapi.WXUtil;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class SharePicPopupWindow2 extends PopupWindow
{

    /**
     * 分享类型
     */
    private int flag;
    private View mMenuView;
    private Button mCancel;
    private GridView mShareGridView;
    private Activity mContext;
    private ShareBeansInfo shareInfo;
    // wx
    private IWXAPI wxAPI;
    private String shareDoufuStr = "快来豆花，你就是我失散多年的基友！【豆花App，女性向创作社区】下载戳：";
    private HttpResponseListener responseLisenter;

    public SharePicPopupWindow2(Activity context)
    {
        super(context);
        this.mContext = context;
        registerShareServices();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_share_layout, null);
        mShareGridView = (GridView) mMenuView.findViewById(R.id.dialog_share_layout_gv);
        mCancel = (Button) mMenuView.findViewById(R.id.dialog_share_cancel);
        TTShareAdapter adapter = new TTShareAdapter(context);
        mShareGridView.setAdapter(adapter);
        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new OnTouchListener()
        {

            public boolean onTouch(View v, MotionEvent event)
            {

                int height = mMenuView.findViewById(R.id.dialog_share_rootLayout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP)
                {
                    if (y < height)
                    {
                        dismiss();
                    }
                }
                return true;
            }
        });
        mCancel.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                dismiss();
            }
        });
        mShareGridView.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
            {
                dismiss();
                int share_social_type = 100;
                switch (position)
                {
                    case TTShareAdapter.SHARE_TO_SINA_WEIBO:
//                        shareInfo.shareUrl = Constant.DOWN_URL_WB;
                        // shareToSinalWeibo();
                        share_social_type = 101;
                        break;

                    case TTShareAdapter.SHARE_TO_WEIXIN:
//                        shareInfo.shareUrl = mContext.getResources().getString(R.string.about_us_office_website_content);
                        // shareToWeixin();
                        share_social_type = 102;
                        break;

                    case TTShareAdapter.SHARE_TO_PENGYOUQUAN:
//                        shareInfo.shareUrl = mContext.getResources().getString(R.string.about_us_office_website_content);
                        // shareToPengyouquan();
                        share_social_type = 103;
                        break;

                   /* case TTShareAdapter.SHARE_TO_TECENT_WEIBO:
                        shareToTecentWeibo();
                        share_social_type = 104;
                        break;*/
                    case TTShareAdapter.SHARE_TO_MESSAGE:
//                        shareInfo.shareUrl = Constant.DOWN_URL_DX;
                        // shareToMessage();
                        share_social_type = 105;
                        break;

                    case TTShareAdapter.SHARE_TO_EMAIL:
//                        shareInfo.shareUrl = Constant.DOWN_URL_YJ;
                        // shareToEmail();
                        share_social_type = 106;
                        break;
                    case TTShareAdapter.SHARE_TO_SYSTEM_MORE:
                        //  shareToSystemMore();
                        break;
                    case TTShareAdapter.SHARE_TO_TECENT_QQ:
//                        shareInfo.shareUrl = Constant.DOWN_URL_QQ;
                        //shareQQ();
                        share_social_type = 107;
                        break;
                    case TTShareAdapter.SHARE_TO_TECENT_SPACE:
//                        shareInfo.shareUrl = Constant.DOWN_URL_QQ;
                        //  shareQQSpace();
                        share_social_type = 108;
                        break;
                    case TTShareAdapter.COPY_THE_SHARE_LINK:
                        //  copyShareInfo();
                        break;
                    default:
                        break;
                }
                shareInfo.setSocial_type(share_social_type);
                HomeMainServices.getInstance().getShareUrlRequest(shareInfo.getId(),shareInfo.getObject_type(),responseLisenter, shareInfo.shareUrl, position);

            }
        });

        responseLisenter = new HttpResponseListener()
        {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response)
            {
                HttpUtil.setOnHandleHttpResponListener(mContext, handleType, response, new HttpUtil.HandleHttpResponListener()
                {
                    @Override
                    public void handleRespon(int handleType, JSONObject data)
                    {
                        String urlId = "";
                        try
                        {
                            urlId = data.getString("id");
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
//                        if (shareInfo.shareUrl.contains("?"))
//                        {
//                            shareInfo.shareUrl += ("&share_id=" + urlId);
//                        } else
//                        {
//                            shareInfo.shareUrl += ("?share_id=" + urlId);
//                        }

                        //  int share_social_type = 100;
                        switch (handleType)
                        {
                            case TTShareAdapter.SHARE_TO_SINA_WEIBO:
                                shareToSinalWeibo();
                                //    share_social_type = 101;
                                break;

                            case TTShareAdapter.SHARE_TO_WEIXIN:
                                shareToWeixin();
                                //  share_social_type = 102;
                                break;

                            case TTShareAdapter.SHARE_TO_PENGYOUQUAN:
                                shareToPengyouquan();
                                //    share_social_type = 103;
                                break;

                   /* case TTShareAdapter.SHARE_TO_TECENT_WEIBO:
                        shareToTecentWeibo();
                        share_social_type = 104;
                        break;*/
                            case TTShareAdapter.SHARE_TO_MESSAGE:
                                shareToMessage();
                                //   share_social_type = 105;
                                break;

                            case TTShareAdapter.SHARE_TO_EMAIL:
                                shareToEmail();
                                //  share_social_type = 106;
                                break;
                            case TTShareAdapter.SHARE_TO_SYSTEM_MORE:
                                shareToSystemMore();
                                break;
                            case TTShareAdapter.SHARE_TO_TECENT_QQ:
                                shareQQ();
                                // share_social_type = 107;
                                break;
                            case TTShareAdapter.SHARE_TO_TECENT_SPACE:
                                shareQQSpace();
                                // share_social_type = 108;
                                break;
                            case TTShareAdapter.COPY_THE_SHARE_LINK:
                                copyShareInfo();
                                break;
                            default:
                                break;
                        }
                        // shareInfo.setSocial_type(share_social_type);
                    }
                });
            }
        };
    }

    private void copyShareInfo()
    {
        if (shareInfo != null && shareInfo.getShareUrl() != null)
        {
            UIUtil.toastMessage(mContext, "复制链接成功");
            TextUtil.copyString2Clipboard(mContext, shareInfo.getShareUrl());
        }
    }



    private void registerShareServices()
    {
        // wx
        wxAPI = WXAPIFactory.createWXAPI(mContext, Constant.WX_APP_ID, true);
        wxAPI.registerApp(Constant.WX_APP_ID);
    }

    public void setShareBeans(ShareBeansInfo shareInfo)
    {
        if (shareInfo.getId() == null || shareInfo.getShareData() == null)
        {
            HomeTopBean shareData = new HomeTopBean();
            shareData.setObject_type("22");
            shareInfo.setId("3");
            shareInfo.setShareData(shareData);
        }
        this.shareInfo = shareInfo;
    }

    public void shareToSinalWeibo()
    {
        String shareText = "";
        switch (shareInfo.getFlag())
        {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                shareText = shareDoufuStr + shareInfo.shareUrl + " @豆花";
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareText=shareInfo.getTitle()+ " " +shareInfo.getDescription()+ " " +shareInfo.getShareUrl();
                shareText = shareInfo.getTitle() + " " + shareInfo.getDescription() + " " + shareChannel(shareInfo.shareUrl, Constant.ShareChannel.SinaWeibo);
                break;
            default:
                break;
        }
        shareInfo.setShartText(shareText);
        Intent intent = new Intent(mContext, SinaWeiboActivity.class);
        intent.putExtra("flag", shareInfo.getFlag());
        intent.putExtra("shareInfo", shareInfo);
        mContext.startActivityForResult(intent, 0);

    }

    public static int wxShareType;

    private void shareToWeixin()
    {
        Bitmap bmp = null;
        switch (shareInfo.getFlag())
        {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                if (bmp == null)
                {
                    bmp = FetchResourceUtil.fetchBitmap(mContext.getResources(), R.drawable.new_icon);
                }
                shareInfo.setShareUrl(shareInfo.shareUrl);
                shareInfo.setTitle("豆花App，女性向创作社区");
                shareInfo.setDescription("：彩虹无罪，有爱万岁。快来豆花，你就是我失散多年的基友！");
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareInfo.setTitle(shareInfo.getShartText());
                shareInfo.setShareUrl(shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.Weixin));
                break;
            default:
                break;
        }
        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = shareInfo.getShareUrl();
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = shareInfo.getTitle();
        msg.mediaObject = webpageObj;
        msg.description = shareInfo.getDescription();
        if (bmp != null)
        {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, WXData.THUMB_WIDTH_SIZE, WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }
        //		msg.description = mPaperDescription;
        WXTextObject textObject = new WXTextObject();
        textObject.text = shareInfo.getTitle();
        ;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneSession; // for wechat friends
        wxShareType = SendMessageToWX.Req.WXSceneSession;
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        wxAPI.sendReq(req);

    }

    private void shareToPengyouquan()
    {

        if (wxAPI.getWXAppSupportAPI() < WXData.PENG_YOU_QUAN_MIN_VERSION_CODE)
        {
            Toast.makeText(mContext, R.string.info_share_pengyouquan_version_too_low, Toast.LENGTH_LONG).show();
            return;
        }
        Bitmap bmp = null;
        switch (shareInfo.getFlag())
        {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                bmp = FetchResourceUtil.fetchBitmap(mContext.getResources(), R.drawable.new_icon);
                shareInfo.setShareUrl(shareInfo.shareUrl);
                shareInfo.setDescription("【有爱万岁】豆花，女性向创作社区");
                shareInfo.setTitle("豆花App，女性向创作社区");
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareInfo.setTitle(shareInfo.getShartText());
                shareInfo.setShareUrl(shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.pengyouquan));
                break;
            default:
                break;
        }
        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = shareInfo.getShareUrl();

        WXMediaMessage msg = new WXMediaMessage();
        msg.title = shareInfo.getTitle();
        msg.mediaObject = webpageObj;
        msg.description = shareInfo.getDescription();
        if (bmp != null)
        {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, WXData.THUMB_WIDTH_SIZE, WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneTimeline; // for pengyou quan
        wxShareType = SendMessageToWX.Req.WXSceneTimeline;
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        wxAPI.sendReq(req);
    }

    private void shareToMessage()
    {
        String smsBody = "";
        switch (shareInfo.getFlag())
        {

            case ShareBeansInfo.OWN_SHARE_FLAG:
                smsBody = "您的好朋友邀请您下载【豆花，女性向创作社区】官网下载：" + shareInfo.shareUrl;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			smsBody=shareInfo.getShartText()+shareInfo.shareUrl;
                //			smsBody=shareInfo.getTitle()+": "+shareInfo.getDescription()+" "+shareInfo.shareUrl;
                smsBody = shareChannel(shareInfo.getTitle() + ": " + shareInfo.getDescription() + " " + shareInfo.shareUrl, Constant.ShareChannel.other);
                break;
        }
        Uri smsToUri = Uri.parse("smsto:");
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", smsBody);
        mContext.startActivity(intent);
    }

    private void shareToEmail()
    {
        String shareText = "";
        String title = "";
        switch (shareInfo.getFlag())
        {

            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "我发现了一个超级合口味的应用";
                shareText = shareDoufuStr + shareInfo.shareUrl + " @豆花";
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                //			shareText=shareInfo.getDescription()+" "+shareInfo.shareUrl;
                shareText = shareChannel(shareInfo.getDescription() + " " + shareInfo.shareUrl, Constant.ShareChannel.other);
                break;
        }

        try
        {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            //			intent.setType("message/rfc882");
            //设置邮件默认地址
            intent.putExtra(Intent.EXTRA_SUBJECT, title);
            intent.putExtra(Intent.EXTRA_TEXT, shareText);
            mContext.startActivity(intent);
        } catch (ActivityNotFoundException e)
        {
            Toast.makeText(mContext, mContext.getString(R.string.info_email_start_failed), Toast.LENGTH_LONG).show();
        }
    }

    private void shareToSystemMore()
    {
        String shareText = "";
        String title = "";
        switch (shareInfo.getFlag())
        {

            case ShareBeansInfo.AETICLE_SHARE_FLAG:
                shareText = mContext.getString(R.string.common_share_tag_prefix_start) + shareInfo.getArticleAuthor() + mContext.getString(R.string.common_share_tag_prefix_end) + "《" + shareInfo.getTitle() + "》 " + mContext.getString(R.string.common_share_tag_prefix_address) + shareInfo.getShareUrl() + " " + "@" + mContext.getString(R.string.app_name);
                title = mContext.getString(R.string.share_article_title);
                break;

        }
        TTLog.s("ShareTopPopupWindow === " + title + "==" + shareText);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.share_title)));

    }

    private void shareQQSpace()
    {
        Bundle params = new Bundle();
        String title = null, summary = null, extStr = null;
        String shareUrl = "";
        String imgUrl = "";
        switch (shareInfo.getFlag())
        {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "豆花，女性向创作社区";
                summary = shareDoufuStr + shareInfo.shareUrl + " @豆花";
                extStr = shareInfo.getShartText() + shareInfo.shareUrl;
                shareUrl = shareInfo.shareUrl;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                summary = shareInfo.getDescription();
                extStr = shareInfo.getDescription();
                //			shareUrl = shareInfo.getShareUrl();
                shareUrl = shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.qZone);
                imgUrl = shareInfo.getImagUrl();
                if (imgUrl == null || imgUrl.equals(""))
                {
                    imgUrl = Constant.LOGO_URL;
                }
                imgUrl = Constant.LOGO_URL;
                break;
            default:
                break;
        }
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 必填
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);// 选填
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);// 必填
        ArrayList<String> imgs = new ArrayList<String>();
        imgs.add(imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgUrl);

        params.putStringArrayList(QQShare.SHARE_TO_QQ_IMAGE_URL, imgs);
        QQService.getInstance().shareToQZone(mContext, params, new IUiListener()
        {

            @Override
            public void onError(UiError arg0)
            {
            }

            @Override
            public void onComplete(Object arg0)
            {
                UIUtil.toastMessage(WeMediaApplication.applicationContext, "分享成功");
            }

            @Override
            public void onCancel()
            {
                //				UIUtil.toastMessage(WeMediaApplication.applicationContext, "已取消分享");
            }
        });

    }

    private void shareQQ()
    {
        Bundle params = new Bundle();
        String title = null, summary = null, extStr = null;
        String shareUrl = "";
        String imgUrl = "";
        switch (shareInfo.getFlag())
        {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "豆花App，女性向创作社区";
                summary = "快来豆花，你就是我失散多年的基友！";
                extStr = shareDoufuStr + shareInfo.shareUrl + " @豆花";
                shareUrl = shareInfo.shareUrl;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                summary = shareInfo.getDescription();
                extStr = shareInfo.getDescription();
                //			shareUrl = shareInfo.getShareUrl();
                shareUrl = shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.qq);
                imgUrl = shareInfo.getImagUrl();
                if (imgUrl == null || imgUrl.equals(""))
                {
                    imgUrl = Constant.LOGO_URL;
                }
                break;
            default:
                break;
        }
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QQShare.SHARE_TO_QQ_EXT_STR, extStr);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "豆花");
        QQService.getInstance().shareToQQ(mContext, params, new IUiListener()
        {

            @Override
            public void onError(UiError arg0)
            {
            }

            @Override
            public void onComplete(Object arg0)
            {
                UIUtil.toastMessage(WeMediaApplication.applicationContext, "分享成功");
            }

            @Override
            public void onCancel()
            {
                //				UIUtil.toastMessage(WeMediaApplication.applicationContext, "已取消分享");
            }
        });

    }

    private String shareChannel(String shareUrl, String channel)
    {
        return shareUrl;

    }
}
